<template>
  <div class="pool-container">
    <div
      v-if="!operateDisabled"
      class="tabs-add"
    >
      <el-button
        typr="primary"
        icon="plus"
        plain
        @click="addPool"
      >
        添加奖池
      </el-button>
    </div>
    <el-tabs
      v-model="poolActiveName"
      type="card"
      @tab-remove="deletePool"
    >
      <el-tab-pane
        v-for="(pool, pIndex) in modelValue"
        :label="pool.name"
        :name="pIndex + ''"
        :closable="pool.defaulted == 0 && !operateDisabled"
      >
        <h3 class="collpase-title">
          <div class="info">
            <span v-show="activityModel !== 'edit' && !activityBaseInfo.id">拖动行可移动奖品顺序</span>
          </div>
          <div v-if="!operateDisabled">
            <el-button
              v-if="activityModel !== 'edit'"
              icon="CopyDocument"
              style="margin-right: 10px"
              @click="copyPool(pIndex)"
            >
              一键复制
            </el-button>
            <template v-if="pool.defaulted == 0">
              <el-button
                icon="edit"
                type="primary"
                style="margin-right: 10px"
                @click="editPool(pIndex)"
              >
                编辑
              </el-button>
            </template>
            <el-dropdown @command="addPrize($event, pIndex)">
              <el-button type="primary">
                添加奖品<el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    v-if="pool.type == 1"
                    :command="0"
                  >
                    谢谢参与
                  </el-dropdown-item>
                  <el-dropdown-item :command="1">
                    商家商品
                  </el-dropdown-item>
                  <el-dropdown-item :command="3">
                    礼品包
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="pool.type == 1"
                    :command="2"
                  >
                    积分
                  </el-dropdown-item>
                  <el-dropdown-item :command="4">
                    优惠券
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
          <template v-else-if="pool.defaulted == 0">
            <el-button
              type="primary"
              style="margin-right: 10px"
              @click="editPool(pIndex)"
            >
              详情
            </el-button>
          </template>
        </h3>
        <div class="table-container">
          <div class="table-header">
            <div
              class="drag-indicator table-cell"
              style="width: 35px"
            />
            <div
              class="expand table-cell"
              style="width: 35px"
            />
            <div
              class="table-cell"
              style="width: 80px"
            >
              序号
            </div>
            <div
              class="table-cell"
              style="width: 90px"
            >
              图片
            </div>
            <div
              class="table-cell"
              style="width: 120px"
            >
              商品名称
            </div>
            <div
              class="table-cell"
              style="width: 80px"
            >
              商品类别
            </div>
            <div
              v-if="pool.type == 1"
              class="table-cell"
              style="width: 80px"
            >
              中奖权重
            </div>
            <div
              class="table-cell"
              style="width: 120px"
            >
              剩余库存/ 总库存（商品）
            </div>
            <div
              v-if="pool.type == 1"
              class="table-cell"
              style="width: 80px"
            >
              默认奖品
            </div>
            <div
              v-if="pool.type == 1"
              class="table-cell"
              style="width: 80px"
            >
              首次必中
            </div>
            <div
              class="table-cell"
              style="width: 80px"
            >
              状态
            </div>
            <div
              class="table-cell"
              style="width: 160px"
            >
              更新时间
            </div>
            <div
              v-if="!operateDisabled"
              class="table-cell"
              style="width: 120px"
            >
              操作
            </div>
          </div>
          <draggable
            v-model="pool.prizeInfos"
            group="people"
            :disabled="false"
            item-key="key"
            @update="(customEvent) => handleDragUpdate(customEvent, pool)"
          >
            <template #item="{ element, index }">
              <div>
                <div
                  class="table-row"
                  :class="{
                    'table-row-mouse-enter': currentMouseEnterIndex === index
                  // noMove:activityModel !== 'edit'
                  }"
                  @mouseenter="handleRowMouseEnter(index)"
                  @mouseleave="handleRowMouseLeave"
                >
                  <div
                    class="table-cell"
                    style="cursor: move;width: 50px"
                  >
                    <template v-if="currentMouseEnterIndex === index">
                      <span
                        class="iconfont icon-tuozhuai"
                        style="font-size: 30px"
                      />
                    </template>
                  </div>
                  <div
                    class="expand table-cell"
                    style="width: 35px"
                  >
                    <div
                      v-if="element.prizeType == 1 || element.prizeType == 3"
                      class="expand-icon"
                      @click="handleExpand(pIndex, index)"
                    >
                      <el-icon>
                        <ArrowDown />
                      </el-icon>
                    </div>
                  </div>
                  <div
                    class="table-cell"
                    style="width: 80px"
                  >
                    {{ index + 1 }}
                  </div>
                  <div
                    class="table-cell"
                    style="width: 90px"
                  >
                    <el-image
                      style="width: 60px; height: 60px"
                      :preview-src-list="[element.thumbnailUrl]"
                      :src="element.thumbnailUrl"
                      preview-teleported
                      fit="contain"
                    />
                  </div>
                  <div
                    class="table-cell"
                    style="width: 120px"
                  >
                    <el-tooltip
                      effect="dark"
                      :content="element.name"
                      placement="top"
                    >
                      {{ element.name }}
                    </el-tooltip>
                  </div>
                  <div
                    class="table-cell"
                    style="width: 80px"
                  >
                    {{ prizeType[element.prizeType] }}
                  </div>
                  <div
                    v-if="pool.type == 1"
                    class="table-cell"
                    style="width: 80px"
                  >
                    {{ element.probability }}
                  </div>
                  <div
                    class="table-cell"
                    style="width: 120px"
                  >
                    {{ element.stock }}/{{ element.stockTotal }}
                  </div>
                  <div
                    v-if="pool.type == 1"
                    class="table-cell"
                    style="width: 80px"
                  >
                    <span v-if="operateDisabled">{{
                      element.defaulted == 1 ? "是" : "否"
                    }}</span>
                    <el-switch
                      v-else
                      v-model="element.defaulted"
                      inline-prompt
                      active-text="是"
                      inactive-text="否"
                      :active-value="1"
                      :inactive-value="0"
                      @change="defaultChange(pIndex, index)"
                    />
                  </div>

                  <div
                    v-if="pool.type == 1"
                    class="table-cell"
                    style="width: 80px"
                  >
                    <span v-if="operateDisabled">{{
                      element.firstPrize == 1 ? "是" : "否"
                    }}</span>
                    <el-switch
                      v-else
                      v-model="element.firstPrize"
                      inline-prompt
                      active-text="是"
                      inactive-text="否"
                      :active-value="1"
                      :inactive-value="0"
                      @change="firstPrizeChange(pIndex, index)"
                    />
                  </div>

                  <div
                    class="table-cell"
                    style="width: 80px"
                  >
                    <span v-if="operateDisabled">{{
                      element.onlineStatus == 1 ? "上架" : "下架"
                    }}</span>
                    <div
                      v-else
                      class="switch"
                      @click="changeStatus(pIndex, index)"
                    >
                      <el-switch
                        :model-value="element.onlineStatus"
                        inline-prompt
                        :active-value="1"
                        :inactive-value="0"
                        active-text="上架"
                        inactive-text="下架"
                      />
                      <div class="cover" />
                    </div>
                  </div>
                  <div
                    class="table-cell"
                    style="width: 160px"
                  >
                    {{
                      element.updateTime
                        ? $filters.dateFormat(element.updateTime)
                        : ""
                    }}
                  </div>
                  <div
                    v-if="!operateDisabled"
                    class="table-cell"
                    style="width: 120px"
                  >
                    <div class="btn-container">
                      <el-button
                        type="primary"
                        link
                        size="small"
                        @click="editPrize(pIndex, index)"
                      >
                        编辑
                      </el-button>
                      <el-button
                        type="primary"
                        link
                        size="small"
                        @click="deletePrize(pIndex, index)"
                      >
                        删除
                      </el-button>
                      <template v-if="activityModel === 'edit'">
                        <el-dropdown
                          placement="top"
                          @command="handleCommand($event, pIndex, index)"
                        >
                          <div style="margin-left: 10px; cursor: pointer">
                            <el-button
                              type="primary"
                              link
                              size="small"
                            >
                              更多
                            </el-button>
                          </div>
                          <template #dropdown>
                            <el-dropdown-menu>
                              <el-dropdown-item
                                v-if="element.onlineStatus === 1"
                                command="inventory"
                              >
                                调整库存
                              </el-dropdown-item>
                              <el-dropdown-item
                                v-if="pool.type == 2 && element.prizeType == 1"
                                command="addspec"
                              >
                                新增规格
                              </el-dropdown-item>
                              <el-dropdown-item
                                v-if="element.prizeType == 3"
                                command="addGiftBagSpec"
                              >
                                新增商品
                              </el-dropdown-item>
                            </el-dropdown-menu>
                          </template>
                        </el-dropdown>
                      </template>
                    </div>
                  </div>
                </div>
                <div
                  v-if="element.prizeSpecifications"
                  v-show="element.expand"
                  class="table-expand_container"
                >
                  <div class="table-header">
                    <div
                      class="table-cell"
                      style="width: 90px"
                    >
                      图片
                    </div>
                    <div
                      class="table-cell"
                      style="width: 120px"
                    >
                      奖品名称
                    </div>
                    <div
                      class="table-cell"
                      style="width: 120px"
                    >
                      售价
                    </div>
                    <div
                      class="table-cell"
                      style="width: 120px"
                    >
                      剩余库存/ 总库存（规格）
                    </div>
                    <div
                      class="table-cell"
                      style="width: 80px"
                    >
                      状态
                    </div>
                    <div
                      v-if="!operateDisabled && activityModel === 'edit'"
                      class="table-cell"
                      style="width: 120px"
                    >
                      操作
                    </div>
                  </div>
                  <!-- 商品 -->
                  <div
                    v-for="(spec, sIndex) in element.prizeSpecifications"
                    v-if="element.prizeType == 1"
                    class="table-row"
                  >
                    <div
                      class="table-cell"
                      style="width: 90px"
                    >
                      <el-image
                        style="width: 60px; height: 60px"
                        :preview-src-list="[spec.thumbnailUrl]"
                        :src="spec.thumbnailUrl"
                        preview-teleported
                        fit="contain"
                      />
                    </div>
                    <div
                      class="table-cell"
                      style="width: 120px"
                    >
                      <el-tooltip
                        effect="dark"
                        :content="spec.name"
                        placement="top"
                      >
                        {{ spec.name }}
                      </el-tooltip>
                    </div>
                    <div
                      class="table-cell"
                      style="width: 120px"
                    >
                      {{
                        spec.priceType == 1 || spec.priceType == 3
                          ? setMoneyConfig(spec.payPrice)
                          : ""
                      }}{{ spec.priceType == 3 ? "+" : ""
                      }}{{
                        spec.priceType == 2 || spec.priceType == 3
                          ? spec.currencyNum + getCurrencyName(spec.currencyId)
                          : ""
                      }}
                    </div>
                    <div
                      class="table-cell"
                      style="width: 120px"
                    >
                      {{ spec.stock }}/{{ spec.totalStock }}
                    </div>
                    <div
                      class="table-cell"
                      style="width: 80px"
                    >
                      <span v-if="operateDisabled">{{
                        spec.onlineStatus == 1 ? "上架" : "下架"
                      }}</span>
                      <div
                        v-else
                        class="switch"
                        @click="changeSpecStatus(pIndex, index, sIndex)"
                      >
                        <el-switch
                          :model-value="spec.onlineStatus"
                          inline-prompt
                          :active-value="1"
                          :inactive-value="0"
                          active-text="上架"
                          inactive-text="下架"
                        />
                        <div class="cover" />
                      </div>
                    </div>
                    <div
                      v-if="activityModel === 'edit'"
                      class="table-cell"
                      style="width: 120px"
                    >
                      <el-button
                        type="primary"
                        link
                        size="small"
                        @click="editSpec(pIndex, index, sIndex)"
                      >
                        编辑
                      </el-button>
                      <el-button
                        type="primary"
                        link
                        size="small"
                        @click="deleteSpec(pIndex, index, sIndex)"
                      >
                        删除
                      </el-button>
                    </div>
                  </div>
                  <!-- 礼品包 -->
                  <template
                    v-for="(bag, bIndex) in element.childPrizes"
                    v-if="element.prizeType == 3"
                  >
                    <div
                      v-for="(spec, sIndex) in bag.prizeSpecifications"
                      class="table-row"
                    >
                      <div
                        class="table-cell"
                        style="width: 90px"
                      >
                        <el-image
                          style="width: 60px; height: 60px"
                          :preview-src-list="[spec.thumbnailUrl]"
                          :src="spec.thumbnailUrl"
                          preview-teleported
                          fit="contain"
                        />
                      </div>
                      <div
                        class="table-cell"
                        style="width: 120px"
                      >
                        <el-tooltip
                          effect="dark"
                          :content="spec.name"
                          placement="top"
                        >
                          {{ spec.name }}
                        </el-tooltip>
                      </div>
                      <div
                        class="table-cell"
                        style="width: 120px"
                      >
                        {{
                          spec.priceType == 1 || spec.priceType == 3
                            ? spec.payPrice + "元"
                            : ""
                        }}{{ spec.priceType == 3 ? "+" : ""
                        }}{{
                          spec.priceType == 2 || spec.priceType == 3
                            ? spec.currencyNum +
                              getCurrencyName(spec.currencyId)
                            : ""
                        }}
                      </div>
                      <div
                        class="table-cell"
                        style="width: 120px"
                      >
                        {{ spec.stock }}/{{ spec.totalStock }}
                      </div>
                      <div
                        class="table-cell"
                        style="width: 80px"
                      >
                        <span v-if="operateDisabled">{{
                          spec.onlineStatus == 1 ? "上架" : "下架"
                        }}</span>
                        <div
                          v-else
                          class="switch"
                          @click="
                            changeSpecStatus(pIndex, index, sIndex, bIndex)
                          "
                        >
                          <el-switch
                            :model-value="spec.onlineStatus"
                            inline-prompt
                            :active-value="1"
                            :inactive-value="0"
                            active-text="上架"
                            inactive-text="下架"
                          />
                          <div class="cover" />
                        </div>
                      </div>
                      <div
                        v-if="activityModel === 'edit'"
                        class="table-cell"
                        style="width: 120px"
                      >
                        <el-button
                          type="primary"
                          link
                          size="small"
                          @click="editSpec(pIndex, index, sIndex, bIndex)"
                        >
                          编辑
                        </el-button>
                        <el-button
                          type="primary"
                          link
                          size="small"
                          @click="deleteSpec(pIndex, index, sIndex)"
                        >
                          删除
                        </el-button>
                      </div>
                    </div>
                  </template>
                </div>
              </div>
            </template>
          </draggable>
          <div
            v-if="!pool.prizeInfos || pool.prizeInfos.length == 0"
            class="empty"
          >
            暂无数据
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
  <!-- 商品配置 -->
  <PrizeForm
    ref="formRef"
    v-model="dialogVisible"
    :detail="form"
    :title="dialogTitle"
    :loading="submitLoading"
    @update="savePrize"
  />
  <!-- 规格配置 -->
  <Dialog
    v-model="showSpec"
    title="编辑规格"
    :loading="submitLoading"
    close-on-click-modal
    @confirm="saveSpec"
  >
    <SpecSetting
      ref="specRef"
      v-model="specForm"
      :pool-type="specForm.poolType"
      :goods-id="specForm.goodsId"
    />
  </Dialog>
  <!-- 礼品包规格配置 -->
  <Dialog
    v-model="showGiftBag"
    title="礼品包商品"
    :loading="submitLoading"
    close-on-click-modal
    @confirm="saveGiftBagSpec"
  >
    <GiftBagSetting
      ref="giftBagSpecRef"
      v-model="giftBagSpecForm"
      :pool-type="giftBagSpecForm.poolType"
      :grant-type="giftBagSpecForm.grantType"
      :stock="giftBagSpecForm.bagStock"
    />
  </Dialog>
  <!-- 选择商品类型 -->
  <SelectGoods
    ref="SelectGoodsRef"
    v-model:show="showSelectGoods"
    table-url="activity/ext/getProductList"
    :table-param="tableParmas"
    stock="allStock"
    @select="handleSelectGoods"
  >
    <template #search>
      <el-tabs
        v-model="goodsFilterParams.defaultStore"
        class="demo-tabs"
      >
        <el-tab-pane
          name="0"
          label="商户商家供货"
        />
        <el-tab-pane
          name="1"
          label="联海供货"
        />
      </el-tabs>
      <!-- <search-bar inline>
        <template #normal> -->
      <el-form
        ref="goodsFilterParamsRef"
        :model="goodsFilterParams"
        inline
      >
        <el-form-item label="商品名称">
          <el-input
            v-model="goodsFilterParams.goodsName"
            placeholder="请输入商品名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="商品分类">
          <!-- <el-select clearable placeholder="请选择商品类型">
              <el-option v-for="(item) in "  :key="item.id"
                :label="item.categoryName"
                :value="item.id" />
            </el-select> -->
          <el-cascader
            :options="productType"
            :props="props1"
            clearable
            @change="productTypeChange"
          />
        </el-form-item>
        <el-form-item label="商家">
          <el-select
            v-model="goodsFilterParams.storeId"
            clearable
            placeholder="请选择商家"
          >
            <el-option
              v-for="(item, key) in merchantList"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="input-range-box">
          <el-form-item
            label="供货价"
            style="margin-right:12px"
            label-width="68px" 
            prop="minCost"
            :rules="rules.minAmount"
          >
            <el-input
              v-model="goodsFilterParams.minCost"
              style="width: 200px;"
              placeholder="请输入最低金额"
              clearable
            />
          </el-form-item>
          <el-form-item
            prop="maxCost"
            :rules="rules.maxAmount"
          >
            <template #label>
              <span>~</span>
            </template>
            <el-input
              v-model="goodsFilterParams.maxCost"
              style="width: 200px;"
              placeholder="请输入最高金额"
              clearable
            />
          </el-form-item>
        </el-form-item>
      </el-form>
      <!-- </template>
      </search-bar> -->
    </template>
  </SelectGoods>
  <!-- 奖池配置 -->
  <Dialog
    v-model="showPoolForm"
    title="配置奖池"
    :loading="submitLoading"
    close-on-click-modal
    @confirm="savePool"
  >
    <el-form
      ref="poolFormRef"
      :model="poolForm"
      :rules="poolRules"
      label-width="auto"
      :disabled="operateDisabled"
    >
      <el-form-item
        label="奖池类型："
        prop="type"
      >
        <el-radio-group v-model="poolForm.type">
          <template v-for="(type, index) in poolType">
            <el-radio :label="type">
              {{
                type == 1 ? "抽奖奖池" : "商品池"
              }}
            </el-radio>
          </template>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="奖池名称："
        prop="name"
      >
        <el-input
          v-model="poolForm.name"
          :minlength="2"
          :maxlength="20"
          show-word-limit
          placeholder="请填写奖池名称"
        />
      </el-form-item>
      <el-form-item label="奖池可见限制：">
        <Limits
          v-model="poolForm.viewOriginal"
          :options="setLimitCompontentList()"
          :disabled="operateDisabled"
        />
      </el-form-item>
    </el-form>
    <template
      v-if="operateDisabled"
      #footer
    >
      <div />
    </template>
  </Dialog>
  <!-- 规格库存配置 -->
  <InventorySetting
    v-model:show="inventoryDialog"
    v-model="inventoryForm"
    :loading="submitLoading"
    @submit="updateSpecStock"
  />
  <!-- 选择优惠券 -->
  <CouponSelector
    v-model:show="showSelectCoupon"
    url="activity/ext/getCouponDefineList"
    @confirm="handleSelectCoupon"
  />
  <!-- 优惠券配置 -->
  <CouponSetting
    v-model:show="showCouponSetting"
    :detail="form"
    :mode="couponSettingMode"
    @update="savePrize"
  />
</template>

<script lang="ts" setup>
import type { PropType } from "vue";
import draggable from "vuedraggable";
import PrizeForm from "./PrizeForm.vue";
import Limits from "@/components/limits/Index.vue";
import SelectGoods from "@/components/goodsCenter/SelectGoods.vue";
import CouponSelector from "@/views/marketingTool/components/CouponSelector.vue"
import SpecSetting from "./SpecForm.vue";
import GiftBagSetting from "./GiftBagForm.vue";
import CouponSetting from "./CouponSetting.vue";
import InventorySetting from "./InventorySetting.vue";
import { prizeType } from "@/config/dictionary";
import { debounceUtils } from "@/utils/index.js";
// , productType
import { deepClone, setMoneyConfig, setLimitCompontentList } from "@/utils";
import {
  getProductDetailApi,
  delPrizeAreaApi,
  editPrizeAreaApi,
  prizeOnlineApi,
  prizeSpeOnlineApi,
  addPrizeApi,
  delPrizeApi,
  updPrizeApi,
  editPrizeSpeStockApi,
  editPrizeSpeApi,
  addPackPrizeSpeApi,
  addPrizeSpeApi,
  getListStoreApi2,
  getGoodsCategory,
  delPrizeSpesApi
} from "@/api/activity";

const route = useRoute();

const props = defineProps({
  modelValue: {
    type: Array as PropType<Array<any>>,
    required: true,
  },
  quote: {
    type: Array,
    default: () => {
      return [];
    },
  },
  poolType: {
    type: Array,
    default: () => {
      return [];
    },
  },
  poolBaseInfo: {
    type: Array,
    default: () => {
      return [];
    },
  },
  pageFlag: {
    type: String,
    default: "",
  },
});
const props1 = {
  checkStrictly: true,
  value: 'id',
  label: 'categoryName'
}
const emits = defineEmits([ "change", "update:modelValue", "edit", "delete", "drag-update" ]),
  activityBaseInfo: any = inject("activityBaseInfo"),
  currencyList: any = inject("currencyList", { value: [] }),
  activityModel: string = inject("activityModel", "");
const merchantList: any = ref([]);
const productType: any = ref([]);
const dialogVisible = ref(false),
  dialogTitle = ref(""),
  showPoolForm = ref(false),
  submitLoading = ref(false),
  showSelectGoods = ref(false),
  showSelectCoupon = ref(false),
  showCouponSetting = ref(false),
  couponSettingMode = ref("create"), // create | edit
  goodsFilterParams = ref<any>({
    defaultStore: 0,
    minCost: null,
    maxCost: null
  }),
  poolForm = ref<any>({}),
  form = ref<any>({}),
  showSpec = ref(false),
  showGiftBag = ref(false),
  specForm = ref<any>({}),
  giftBagSpecForm = ref<any>({}),
  inventoryForm = ref<any>({}),
  inventoryDialog = ref(false),
  poolActiveName = ref("0");

const tableParmas = ref<any>({
  defaultStore: 0,
  minCost: null,
  maxCost: null
})

const searchList = debounceUtils(() => {
  SelectGoodsRef.value.search()
}, 800)
const SelectGoodsRef = ref()
const goodsFilterParamsRef = ref()
watch(goodsFilterParams, () => {
  goodsFilterParamsRef.value?.validate((valid:boolean) => {
    if (valid){
      tableParmas.value = { ...goodsFilterParams.value }
      tableParmas.value.minCost = goodsFilterParams.value.minCost ? (goodsFilterParams.value.minCost) * 100 : null
      tableParmas.value.maxCost = goodsFilterParams.value.maxCost ? (goodsFilterParams.value.maxCost) * 100 : null
      searchList()
    }
  })
}, { deep: true })
watch(showSelectGoods, (val) => {
  if (!val){
    goodsFilterParamsRef.value?.resetFields()
  }
})

const poolFormRef = ref(),
  specRef = ref(),
  giftBagSpecRef = ref();

let currentModifyPrize: number = -1,
  currentModifyPool = -1,
  currentModifySpec = -1,
  poolRules = {
    name: [ { required: true, message: "请输入奖池名称", trigger: "blur" } ],
    type: [ { required: true, message: "请选择奖池类型", trigger: "change" } ],
  };

const operateDisabled = computed(() => {
  return props.modelValue[0]
    ? props.modelValue[0].id && activityModel !== "edit"
    : false;
});
const productTypeChange = (value: any) => {
  if (value.length) {
    goodsFilterParams.value.productCategory = value[value.length - 1]
  } else {
    goodsFilterParams.value.productCategory = ''
  }

}
//   初始化奖池数据
const createPool = (base: any) => {
  let pool: any = {};

  pool = {
    defaulted: base.defaulted,
    firstPrize: base.firstPrize,
    type: base.type,
    pageFlag: props.pageFlag,
    name: `${base.defalut ? "默认" : ""}${base.name}`,
    uid: `${props.pageFlag}-pool-${new Date().getTime()}`,
    prizeInfos: [],
    viewExpression: "",
    viewOriginal:
      base.viewOriginal && typeof base.viewOriginal === "string"
        ? JSON.parse(base.viewOriginal)
        : base.viewOriginal,
  };
  // 抽奖奖池默认有谢谢惠顾
  if (base.type == 1) {
    pool.prizeInfos.push({
      name: "谢谢参与",
      thumbnailUrl:
        "https://static.lianhaikeji.com/unimall/B3EA587641F749408E310DE83DC956B7.png",
      onlineStatus: 0,
      defaulted: 1,
      firstPrize: 0,
      prizeType: 0,
      probability: 1,
      uid: `${props.pageFlag}-prize-${new Date().getTime()}`,
    });
  }

  return pool;
};

// 查询积分名称
const getCurrencyName = (id: number | string) => {
  let currency = currencyList.value.find((item: any) => item.id == id);
  if (currency) {
    return currency.name;
  } else {
    return "";
  }
};

//   添加奖品
const addPrize = (command: number, index: number) => {
  let pool = props.modelValue[index];

  let actType = props.poolBaseInfo.find((info) => info.type === pool.type);
  // 奖池上架商品数量限制
  if (
    actType.max &&
    pool.prizeInfos.filter((item: any) => item.onlineStatus == 1).length >=
    actType.max
  ) {
    ElNotification.error({
      message: `最多可添加${actType.max}个上架奖品`,
    });
    return;
  }
  currentModifyPrize = -1;
  currentModifyPool = index;
  // 谢谢惠顾
  if (command == 0) {
    form.value = {
      name: "谢谢参与",
      thumbnailUrl:
        "https://static.lianhaikeji.com/unimall/B3EA587641F749408E310DE83DC956B7.png",
    };
  }
  // 商品
  else if (command == 1) {
    getMerchantList();
    getProductType();
    form.value = {
      prizeSpecifications: [
        {
          onlineStatus: 1,
          uid: `${pool.pageFlag}-spec-${new Date().getTime()}`,
        },
      ],
    };
  }
  // 积分
  else if (command == 2) {
    form.value = {
      type: "currency",
      prizeSpecifications: [
        {
          type: "currency",
          onlineStatus: 1,
          uid: `${pool.pageFlag}-spec-${new Date().getTime()}`,
        },
      ],
    };
  }
  // 礼品包
  else if (command == 3) {
    form.value = {
      packNum: -1,
      childPrizes: [],
      type: "pack",
      prizeSpecifications: [
        {
          onlineStatus: 1,
          type: "pack",
          uid: `${pool.pageFlag}-bag-${new Date().getTime()}`,
        },
      ],
    };
  } 
  // 优惠券
  else if (command == 4) {
    console.log("新增优惠券！！！")
    form.value.actId = activityBaseInfo.value.id // 新增时为undefined
    couponSettingMode.value = 'create'
  }  
  // 公共属性
  form.value.poolType = pool.type;
  form.value.prizeType = command;
  if (activityModel === 'edit'){
    form.value.onlineStatus = 0; //商品默认为下架状态
  } else {
    form.value.onlineStatus = 1; //商品默认为下架状态
  }
  
  form.value.uid = `${pool.pageFlag}-prize-${new Date().getTime()}`;

  if (command == 1) {
    showSelectGoods.value = true;
  } else if (command == 4) {
    // 选择优惠券 弹窗
    showSelectCoupon.value = true;
  }  else {
    dialogVisible.value = true
  }

  dialogTitle.value = `新增${prizeType[command]}`;
};


// 编辑奖品
const editPrize = (pIndex: number, index: number) => {
  currentModifyPrize = index;
  currentModifyPool = pIndex;
  let pool = props.modelValue[pIndex];
  let prize = pool.prizeInfos[index];
  form.value = { ...prize, poolType: pool.type };

  console.log("编辑 => form.value", form.value)
  // 优惠券
  if (form.value.prizeType === 4) {
    showCouponSetting.value = true
    couponSettingMode.value = 'edit'
    return
  }

  dialogVisible.value = true;
  dialogTitle.value = `编辑商品`;
};

// 保存奖品
const savePrize = async (val: any) => {
  console.log("save prize", val)
  let pool = props.modelValue[currentModifyPool];
  if (activityModel === "edit") {
    submitLoading.value = true;
    let api = val.id === undefined ? addPrizeApi : updPrizeApi;
    const rs = await api(
      Object.assign({ actId: activityBaseInfo.value.id, areaId: pool.id }, val)
    );
    submitLoading.value = false;
    if (rs.code == 200) {
      {
        val.id = rs.payload.id;
        ElNotification({
          message: "保存成功",
          type: "success",
        });
      }
    } else return;
  }

  if (currentModifyPrize >= 0) {
    pool.prizeInfos[currentModifyPrize] = val;
  } else {
    if (!pool.prizeInfos) pool.prizeInfos = [];
    pool.prizeInfos.push(val);
    currentModifyPrize = pool.prizeInfos.length - 1;
  }
  dialogVisible.value = false;
  //默认奖品
  if (pool.type == 1 && !pool.actId) {
    let probability = checkProbability(currentModifyPool);
    if (probability <= 100)
      defaultChange(currentModifyPool, currentModifyPrize);
  }
  //首次必中
  if (pool.type == 1 && !pool.actId) {
    firstPrizeChange(currentModifyPool, currentModifyPrize);
  }
  changePrize();
};

// 删除奖品
const deletePrize = (pIndex: number, index: number) => {
  let status = allowDel(pIndex, index, -1);
  if (!status) return;
  let pool = props.modelValue[pIndex];
  let prize = pool.prizeInfos[index];
  ElMessageBox.confirm(`确认删除【${prize.name}】吗？`, "删除提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      if (activityModel === "edit") {
        const rs = await delPrizeApi({ id: prize.id });
        if (rs.code != 200) return;
      }
      pool.prizeInfos.splice(index, 1);
      checkProbability(pIndex);
      changePrize();
    })
    .catch(() => { });
};

// 选择商品
const handleSelectGoods = async (row: any) => {
  const rs = await getProductDetailApi({ id: row.productId });
  if (rs.code == 200) {
    showSelectGoods.value = false;
    form.value.goodsId = row.productId;
    form.value.type = rs.payload.productType;
    form.value.storeId = rs.payload.storeId;
    form.value.storeName = rs.payload.storeName;
    form.value.storePhone = rs.payload.storePhone;
    form.value.name = rs.payload.productName;
    form.value.thumbnailUrl = rs.payload.img;
    form.value.originalPrice = row.originalPrice;
    form.value.bannerImages = rs.payload.bannerImages;
    form.value.detailText = rs.payload.detailText;
    form.value.description = rs.payload.description;
    form.value.dir = rs.payload.description;
    // 礼品包商品
    if (form.value.isGiftBag === true) {
      form.value.prizeSpecifications[0].type = rs.payload.productType;
      giftBagSpecForm.value = deepClone(form.value);
      showGiftBag.value = true;
    } else {
      dialogVisible.value = true;
    }
  }
};

// 选择优惠券
const handleSelectCoupon = (row) => {
  console.log("选择了优惠券！！！", row)
  showSelectCoupon.value = false;
  // TODO 为form赋值
  form.value.couponDetail = row;

  showCouponSetting.value = true
}

// 判断商品是否可删除、下架
const allowDel = (pIndex: number, index: number, sIndex: number): boolean => {
  let pool = props.modelValue[pIndex];
  if (activityModel === "edit" && activityBaseInfo.value.status == 0)
    return true;
  if (props.quote.length > 0) {
    let poolId = pool.id || pool.uid;
    let prizeId = pool.prizeInfos[index].id || pool.prizeInfos[index].uid;

    let prize = props.quote.find(
      (item: any) => item.poolId == poolId && item.prizeId == prizeId
    );

    if (prize) {
      if (sIndex != -1) {
        // 规格下架
        let specId =
          pool.prizeInfos[index].prizeSpecifications[sIndex].id ||
          pool.prizeInfos[index].prizeSpecifications[sIndex].uid;
        let spec = props.quote.find(
          (item: any) =>
            item.poolId == poolId &&
            item.prizeId == prizeId &&
            item.specId == specId
        );
        if (!spec) return true;
      }
      ElMessageBox.alert(
        "该商品正在被其他配置使用，请先删除该引用",
        "温馨提示",
        {
          confirmButtonText: "我知道了",
        }
      );
      return false;
    }
  }
  return true;
};

// 切换默认奖品（默认奖品只能有一个）
const defaultChange = (pIndex: number, index: number) => {
  let pool = props.modelValue[pIndex];
  if (activityModel === "edit") {
    currentModifyPool = pIndex;
    currentModifyPrize = index;
    savePrize(pool.prizeInfos[index]);
    return;
  }
  if (pool.prizeInfos[index].defaulted == 0) {
    changePrize();
    return;
  }
  pool.prizeInfos.forEach((item: any, i: number) => {
    if (i !== index) {
      pool.prizeInfos[i].defaulted = 0;
    }
  });
  changePrize();
};
const firstPrizeChange = (pIndex: number, index: number) => {
  let pool = props.modelValue[pIndex];
  if (activityModel === "edit") {
    currentModifyPool = pIndex;
    currentModifyPrize = index;
    savePrize(pool.prizeInfos[index]);
    return;
  }
  if (pool.prizeInfos[index].firstPrize == 0) {
    changePrize();
    return;
  }
  pool.prizeInfos.forEach((item: any, i: number) => {
    if (i !== index) {
      pool.prizeInfos[i].firstPrize = 0;
    }
  });
  changePrize();
};

// 修改商品上下架，商品概率超过100%需要提醒（仅抽奖区域需要判断）,商品被配置为奖励则不可下架
const changeStatus = async (pIndex: number, index: number) => {
  let pool = props.modelValue[pIndex];
  let currentPrize: any = pool.prizeInfos[index];

  //   是否允许下架
  if (pool.type == 2 && currentPrize.onlineStatus == 1) {
    let status = allowDel(pIndex, index, -1);
    if (!status) {
      return;
    }
  } else if (pool.type == 1) {
    checkProbability(pIndex);
  }

  let newStatus = currentPrize.onlineStatus == 1 ? 0 : 1;
  if (activityModel === "edit") {
    if (newStatus == 0) {
      ElMessageBox.confirm(
        "商品下架后，商品规格库存将全部归还，请确认是否下架此商品？",
        "温馨提示",
        {
          confirmButtonText: "下架",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          prizeOnline(currentPrize, newStatus);
        })
        .catch(() => { });
    } else {
      if (currentPrize.prizeType === 0) {
        prizeOnline(
          {
            id: currentPrize.id,
          },
          newStatus
        );
      } else {
        editInventory(
          pIndex,
          index,
          currentPrize.prizeType == 3 ? "bagStatus" : "goodsStatus"
        );
      }
    }
  } else {
    currentPrize.onlineStatus = newStatus;
    changePrize();
  }
};

// 商品上下架
const prizeOnline = async (prize: any, status: number) => {
  const rs = await prizeOnlineApi({
    id: prize.id,
    onlineStatus: status,
    prizeSpes: (prize.type === "bagStatus" ? [ prize.defaultSpec ] : [])
      .concat(prize.prizeSpecifications || [])
      .map((item: any) => {
        return {
          id: item.id,
          onlineStatus: item.onlineStatus,
          stock: item.num || 0,
          type: item.stype,
        };
      }),
  });
  if (rs.code == 200) {
    ElNotification({
      message: "修改成功",
      type: "success",
    });
    changePrize();
  }
  return rs;
};

// 计算抽奖概率
const checkProbability = (pIndex: number) => {
  return 100;   // fix error: unreachable code
  // fix error: unreachable code
  // let pool = props.modelValue[pIndex];
  // let totalRate = 0;
  // totalRate = pool.prizeInfos.reduce((num: number, item: any) => {
  //   if (item.onlineStatus == 1 && item.prizeType != 0) {
  //     return num + Number(item.probability);
  //   }
  //   return num;
  // }, 0);

  // if (totalRate > 100) {
  //   ElNotification.error({
  //     message: `【${pool.name}】中奖权重不能超过100%`,
  //   });

  //   return totalRate;
  // }

  // let validPrize = pool.prizeInfos.filter(
  //   (item: any) => item.prizeType == 0 && item.onlineStatus == 1
  // );
  // if (validPrize && validPrize.length > 0) {
  //   let validRate = Number(((100 - totalRate) / validPrize.length).toFixed(2));
  //   for (let i = 0; i < validPrize.length; i++) {
  //     validPrize[i].probability = validRate;
  //     totalRate += validRate;
  //   }
  // }

  // return Number(totalRate.toFixed(1));
};

// 切换规格展开收起状态
const handleExpand = (pIndex: number, index: number) => {
  props.modelValue[pIndex].prizeInfos[index].expand =
    !props.modelValue[pIndex].prizeInfos[index].expand;
};

// 修改规格上下架
const changeSpecStatus = async (
  pIndex: number,
  index: number,
  sIndex: number,
  bIndex?: number
) => {
  let pool = props.modelValue[pIndex];
  let prize = pool.prizeInfos[index];
  let spec = prize.prizeSpecifications[sIndex];
  if (prize.prizeType == 3) {
    spec = prize.childPrizes[bIndex].prizeSpecifications[sIndex];
  }

  // 是否允许下架
  if (pool.type == 2 && spec.onlineStatus == 1) {
    let status = allowDel(pIndex, index, sIndex);
    if (!status) {
      return;
    }
  }

  let newStatus = spec.onlineStatus == 1 ? 0 : 1;

  // 商品管理
  if (activityModel === "edit") {
    if (newStatus == 0) {
      ElMessageBox.confirm(
        "规格下架后，规格库存将全部归还，请确认是否下架此规格？",
        "温馨提示",
        {
          confirmButtonText: "下架",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          const rs = await prizeSpeOnlineApi({
            id: spec.id,
            onlineStatus: newStatus,
            stock: 0,
          });
          if (rs.code == 200) {
            changePrize();
          }
        })
        .catch(() => { });
    } else {
      editInventory(
        pIndex,
        index,
        prize.prizeType == 3 ? "bagSpecStatus" : "specStatus",
        sIndex,
        bIndex
      );
    }
  } else {
    if (prize.prizeType == 1)
      prize.prizeSpecifications[sIndex].onlineStatus = newStatus;
    else if (prize.prizeType == 3) {
      prize.childPrizes[bIndex].onlineStatus = newStatus;
      prize.childPrizes[bIndex].prizeSpecifications[sIndex].onlineStatus =
        newStatus;
    }
  }
  changePrize()
};

// 新增规格
const addSpec = (pIndex: number, index: number) => {
  currentModifyPrize = index;
  currentModifyPool = pIndex;
  currentModifySpec = -1;
  let pool = props.modelValue[pIndex];
  let prize = pool.prizeInfos[index];
  specForm.value = {
    priceType: 1,
    payPrice: 0,
    onlineStatus: 0,
    uid: `${pool.pageFlag}-spec-${new Date().getTime()}`,
    poolType: pool.type,
    goodsId: prize.goodsId,
  };
  showSpec.value = true;
};

// 新增礼品包规格
const addGiftBagSpec = (pIndex: number, index: number) => {
  currentModifyPrize = index;
  currentModifyPool = pIndex;
  currentModifySpec = -1;
  let pool = props.modelValue[pIndex];
  let prize = pool.prizeInfos[index];
  form.value = {
    poolType: pool.type,
    prizeType: 2,
    onlineStatus: 1,
    isGiftBag: true,
    uid: `${pool.pageFlag}-bag-${new Date().getTime()}`,
    prizeSpecifications: [
      {
        onlineStatus: 1,
        uid: `${pool.pageFlag}-bag-spec-${new Date().getTime()}`,
      },
    ],
    packNum: -1,
    bagStock: prize.stock,
  };
  showSelectGoods.value = true;
};

// 编辑规格
const editSpec = (
  pIndex: number,
  index: number,
  sIndex: number,
  bIndex?: number
) => {
  currentModifyPrize = index;
  currentModifyPool = pIndex;
  currentModifySpec = sIndex;
  let pool = props.modelValue[pIndex];
  let prize = pool.prizeInfos[index];

  if (prize.prizeType === 3) {
    giftBagSpecForm.value = {
      ...prize.childPrizes[bIndex as number],
      poolType: pool.type,
    };
    showGiftBag.value = true;
  } else {
    specForm.value = {
      ...prize.prizeSpecifications[sIndex],
      payPrice: Number(
        ((prize.prizeSpecifications[sIndex].payPrice || 0) / 100).toFixed(2)
      ),
      poolType: pool.type,
      goodsId: prize.goodsId,
    };
    showSpec.value = true;
  }
};

// 保存规格
const saveSpec = async () => {
  try {
    let specInfo = await specRef.value.check();
    let pool = props.modelValue[currentModifyPool];
    let prize = pool.prizeInfos[currentModifyPrize];
    let api = specInfo.id === undefined ? addPrizeSpeApi : editPrizeSpeApi;

    const rs = await api(
      Object.assign(
        {
          actId: activityBaseInfo.value.id,
          areaId: pool.id,
          prizeId: prize.id,
          type: prize.type,
        },
        specInfo
      )
    );
    if (rs.code == 200) {
      ElNotification({
        message: "保存成功",
        type: "success",
      });
      showSpec.value = false;
      changePrize();
    }
  } catch (e) {
    console.log("error", e);
  }
};

// 保存礼品包规格
const saveGiftBagSpec = async () => {
  try {
    submitLoading.value = true;
    let specInfo = await giftBagSpecRef.value.check();
    let pool = props.modelValue[currentModifyPool];
    let prize = pool.prizeInfos[currentModifyPrize];
    let api = specInfo.id === undefined ? addPackPrizeSpeApi : updPrizeApi;
    const rs = await api(
      Object.assign(
        {
          actId: activityBaseInfo.value.id,
          areaId: pool.id,
          parentId: prize.id,
        },
        specInfo
      )
    );
    if (rs.code == 200) {
      ElNotification({
        message: "保存成功",
        type: "success",
      });

      showGiftBag.value = false;
      submitLoading.value = false;
      changePrize();
    }
  } catch (e) {
    console.log("error", e);
  }
};

// 删除规格
const deleteSpec = (pIndex: number, index: number, sIndex: number) => {
  let status = allowDel(pIndex, index, sIndex);
  if (!status) return;
  let pool = props.modelValue[pIndex];
  let prize = pool.prizeInfos[index];
  let spec = prize.prizeSpecifications[sIndex];
  ElMessageBox.confirm(`确认删除【${spec.name}】吗？`, "删除提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      if (activityModel === "edit") {
        const rs = await delPrizeSpesApi({ id: spec.id });
        if (rs.code == 200) {
          ElNotification({
            message: "删除成功",
            type: "success",
          });
        } else return;
      } else prize.prizeSpecifications.splice(index, 1);
      changePrize();
    })
    .catch(() => { });
};

// 调整库存/上下架
const editInventory = (
  pIndex: number,
  index: number,
  type = "stock",
  sIndex?: number,
  bIndex?: number
) => {
  currentModifyPool = pIndex;
  currentModifyPrize = index;

  let prizeInfo: any = deepClone(props.modelValue[pIndex].prizeInfos[index]);
  prizeInfo.type = type;
  // 调整库存
  if (type === "stock") {
    if (prizeInfo.prizeType == 3) {
      prizeInfo.defaultSpec = prizeInfo.prizeSpecifications[0];
      prizeInfo.defaultSpec.specStock = Infinity;
      prizeInfo.prizeSpecifications = prizeInfo.childPrizes.reduce(
        (list: Array<any>, prize: any) => {
          return list.concat(
            prize.prizeSpecifications.filter(
              (item: any) => item.onlineStatus === 1
            )
          );
        },
        []
      );
    } else {
      prizeInfo.prizeSpecifications = prizeInfo.prizeSpecifications.filter(
        (item: any) => item.onlineStatus == 1
      );
    }
  }
  // 商品规格上架
  else if (type == "specStatus" && sIndex !== undefined) {
    prizeInfo.prizeSpecifications = [
      prizeInfo.prizeSpecifications[sIndex as number],
    ];
  }
  // 礼品包规格上架
  else if (type == "bagSpecStatus" && bIndex !== undefined) {
    prizeInfo.defaultSpec = prizeInfo.prizeSpecifications[0];
    prizeInfo.defaultSpec.specStock = Infinity;
    prizeInfo.prizeSpecifications = [
      prizeInfo.childPrizes[bIndex].prizeSpecifications[sIndex as number],
    ];
  }
  // 礼品包上架
  else if (type == "bagStatus") {
    let prizeSpecList = prizeInfo.childPrizes.reduce(
      (list: Array<any>, item: any) => {
        return list.concat(item.prizeSpecifications);
      },
      []
    );
    prizeInfo.defaultSpec = prizeInfo.prizeSpecifications[0];
    prizeInfo.defaultSpec.specStock = Infinity;
    prizeInfo.defaultSpec.onlineStatus = 1;
    prizeInfo.prizeSpecifications = prizeSpecList;
  }
  // 积分规格预库存
  if (prizeInfo.prizeType == 2) {
    prizeInfo.prizeSpecifications[0].specStock = Infinity;
  }

  inventoryForm.value = prizeInfo;
  inventoryDialog.value = true;
};

// 保存调整库存/上下架
const updateSpecStock = async (val: any) => {
  submitLoading.value = true;
  let rs = null;
  // 规格上下架
  if (val.type === "specStatus" || val.type === "bagSpecStatus") {
    let spec = val.prizeSpecifications[0];
    rs = await prizeSpeOnlineApi({
      id: spec.id,
      onlineStatus: spec.onlineStatus,
      stock: spec.num || 0,
    });
  }
  // 商品上下架
  else if (val.type === "goodsStatus" || val.type === "bagStatus") {
    let rs2 = await prizeOnline(val, 1);
    if (rs2.code == 200) inventoryDialog.value = false;
  }
  // 修改库存
  else if (val.type === "stock") {
    rs = await editPrizeSpeStockApi({
      id: val.id,
      prizeSpes: (val.prizeType === 3 ? [ val.defaultSpec ] : [])
        .concat(val.prizeSpecifications || [])
        .map((item: any) => {
          return {
            id: item.id,
            onlineStatus: item.onlineStatus,
            num: item.num || 0,
            stype: item.stype,
          };
        }),
    });
  }
  if (rs && rs.code == 200) {
    ElNotification({
      message: "保存成功",
      type: "success",
    });
    changePrize();
    inventoryDialog.value = false;
  }
  submitLoading.value = false;
};

const handleCommand = (command: string, pIndex: number, index: number) => {
  if (command === "inventory") {
    editInventory(pIndex, index);
  } else if (command === "addspec") {
    addSpec(pIndex, index);
  } else if (command === "addGiftBagSpec") {
    addGiftBagSpec(pIndex, index);
  }
};

// 新建奖池
const addPool = () => {
  currentModifyPool = -1;
  nextTick(() => {
    if (poolFormRef.value) poolFormRef.value.resetFields();
    poolForm.value = {
      defaulted: 0,
      viewOriginal: {},
    };
    showPoolForm.value = true;
  });
};

// 编辑奖池
const editPool = (index: number) => {
  currentModifyPool = index;
  nextTick(() => {
    if (poolFormRef.value) poolFormRef.value.resetFields();
    poolForm.value = deepClone(props.modelValue[index]);
    poolForm.value.viewOriginal =
      typeof poolForm.value.viewOriginal === "string" &&
        poolForm.value.viewOriginal
        ? JSON.parse(poolForm.value.viewOriginal)
        : poolForm.value.viewOriginal || {};
    showPoolForm.value = true;
  });
};

// 复制奖池
const copyPool = (index: number) => {
  let pool: any = deepClone(props.modelValue[index]);
  pool.defaulted = 0;
  pool.name = `${pool.name}—复制`;
  pool.uid = `${props.pageFlag}-pool-${new Date().getTime()}`;
  pool.prizeInfos.forEach((item: any, index: number) => {
    item.uid = `${pool.pageFlag}-prize-${index}-${new Date().getTime()}`;
    if (item.prizeSpecifications) {
      item.prizeSpecifications.forEach((spec: any, sIndex: number) => {
        spec.uid = `${pool.pageFlag}-spec-${sIndex}-${new Date().getTime()}`;
      });
    }
  });
  props.modelValue.push(pool);
  poolActiveName.value = (props.modelValue.length - 1).toString();
  changePrize();
};

// 保存奖池
const savePool = () => {
  poolFormRef.value.validate(async (valid: any, invalidFields: any) => {
    if (valid) {
      let pool: any = deepClone(poolForm.value);
      if (currentModifyPool == -1) {
        pool = createPool(Object.assign({}, pool, { defaulted: 0 }));
      }
      pool.viewOriginal =
        typeof pool.viewOriginal === "string" || !pool.viewOriginal
          ? pool.viewOriginal
          : JSON.stringify(pool.viewOriginal);

      if (activityModel === "edit") {
        pool.actId = activityBaseInfo.value.id;
        submitLoading.value = true;
        const rs = await editPrizeAreaApi(pool);
        submitLoading.value = false;
        if (rs.code != 200) return;
        else pool.id = rs.payload.id;
      }
      if (currentModifyPool == -1) {
        props.modelValue.push(pool);
        poolActiveName.value = (props.modelValue.length - 1).toString();
      } else props.modelValue[currentModifyPool] = deepClone(pool);
      showPoolForm.value = false;
      changePrize();
    }
  });
};

// 删除奖池
const deletePool = (index: number | string) => {
  let delIndex = Number(index);
  let pool = props.modelValue[delIndex];
  if (pool.defaulted == 1) {
    ElNotification.error({
      message: "默认奖池不能删除",
    } as any);
    return;
  }
  ElMessageBox.confirm(`确认删除【${pool.name}】吗？`, "删除提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      // 商品管理模式调删除接口
      if (activityModel === "edit") {
        pool.delLoading = true;
        const rs = await delPrizeAreaApi({ id: pool.id });
        pool.delLoading = false;
        if (rs.code != 200) return;
      }
      props.modelValue.splice(delIndex, 1);
      if (
        index == poolActiveName.value &&
        index > props.modelValue.length - 1
      ) {
        poolActiveName.value = (delIndex - 1).toString();
      }
      changePrize();
    })
    .catch(() => { });
};

// 更新奖池数据
const changePrize = () => {
  emits("update:modelValue", props.modelValue);
  emits("change");
};

const handleDragUpdate = (customEvent: any, pool: any) => {
  pool.prizeInfos.forEach((item: any, index: number) => {
    item.sorted = index + 1;
  })

  emits("drag-update", pool)
}

const currentMouseEnterIndex = ref(-1)
const handleRowMouseEnter = (index: number) => {
  currentMouseEnterIndex.value = index
}

const handleRowMouseLeave = () => {
  currentMouseEnterIndex.value = -1
}

// 检查奖池数据
const check = (checkValid = false, checkNum = true) => {
  return new Promise((resolve, reject) => {
    for (let i = 0; i < props.modelValue.length; i++) {
      let pool = props.modelValue[i];
      if (!pool.prizeInfos) pool.prizeInfos = [];
      //   抽奖奖池
      if (pool.type == 1) {
        // 设置了中奖限制则必须配置谢谢参与类型奖品
        if (checkValid) {
          let validPrize = pool.prizeInfos.filter(
            (item: any) => item.prizeType === 0
          );
          let onlineValid = validPrize.find(
            (item: any) => item.onlineStatus == 1
          );
          let defaultValid = validPrize.find(
            (item: any) => item.defaulted == 1
          );
          if (
            !validPrize ||
            validPrize.length == 0 ||
            !onlineValid ||
            !defaultValid
          ) {
            reject(
              `你限制了中奖次数，请在【${pool.name}】中至少配置一个上架状态的谢谢参与，并且设置为默认奖品`
            );
          }
        }
        let rs = checkProbability(i);
        if (rs < 100) reject(`【${pool.name}】奖品概率不足100%`);
        else if (rs > 100) reject(`【${pool.name}】奖品概率不能超过100%`);
      }
      // 检查奖池奖品数量
      if (checkNum) {
        let actType = props.poolBaseInfo.find(
          (info) => info.type === pool.type
        );
        if (
          actType.max &&
          pool.prizeInfos.filter((item: any) => item.onlineStatus == 1).length >
          actType.max
        ) {
          reject(`【${pool.name}】最多可添加${actType.max}个上架奖品`);
        } else if (
          actType.min &&
          pool.prizeInfos.filter((item: any) => item.onlineStatus == 1).length <
          actType.min
        ) {
          reject(`【${pool.name}】至少需要添加${actType.min}个上架奖品`);
        }
      }
    }
    resolve(true);
  });
};
// 获取商家列表
const getMerchantList = async () => {
  const rs = await getListStoreApi2({
    defaultStore: goodsFilterParams.value.defaultStore
  });
  if (rs.code == 200) {
    merchantList.value = rs.payload.map((item: any) => ({
      ...item,
      label: item.storeName,
      value: item.id,
    }));
  }
};
// 获取分类
const getProductType = async () => {
  const rs = await getGoodsCategory({
    defaultStore: goodsFilterParams.value.defaultStore
  });
  if (rs.code == 200) {
    productType.value = rs.payload
  }
};

watch(() => goodsFilterParams.value.defaultStore, (val) => {
  if (val) {
    goodsFilterParams.value.goodsName = '';
    goodsFilterParams.value.storeId = '';
    goodsFilterParams.value.productCategory = '';
    getMerchantList()
    getProductType()
  }
}, { deep: true });
defineExpose({ check, addPool, addPrize });

const rules = {
  minAmount: [ {
    trigger: 'blur',
    validator: (rule, value, callback) => {
      if (value){
        if (!/^(([1-9]\d*)|(0{1}))(\.\d{1,2})?$/.test(value)){
          callback('请输入正确格式,保留两位小数!')
        } else if (+value > 9999999999){
          callback('超过上限【99,9999,9999】')
        } else if (goodsFilterParams.value.maxCost && +value > goodsFilterParams.value.maxCost){
          callback('请输入正确的范围!')
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
  }
  ],
  maxAmount: [ {
    trigger: 'blur',
    validator: (rule, value, callback) => {
      if (value){
        if (!/^(([1-9]\d*)|(0{1}))(\.\d{1,2})?$/.test(value)){
          callback('请输入正确格式,保留两位小数!')
        } else if (+value > 9999999999){
          callback('超过上限【99,9999,9999】')
        } else if (goodsFilterParams.value.minCost && +value < goodsFilterParams.value.minCost){
          callback('请输入正确的范围!')
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
  } ]
}
</script>

<style lang="scss" scoped>
.tabs-add {
  float: right;
  position: relative;
  z-index: 1;
}

.table-container {
  width: 100%;
  overflow-x: auto;
}

.collpase-title {
  position: relative;
  padding-left: 10px;
  font-size: 16px;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .info {
    flex: 1;

    span {
      font-size: 13px;
      color: #909399;
      margin-left: 10px;
      font-weight: normal;
    }
  }
}

.table-header {
  display: inline-flex;
  min-width: 100%;
  border-bottom: 1px solid #e4e7ed;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  min-height: 40px;
  background-color: #f4f5f9;

  .table-cell {
    text-align: center;
    flex-shrink: 0;
  }
}

.table-row {
  display: inline-flex;
  min-width: 100%;
  border-bottom: 1px solid #e4e7ed;
  align-items: center;
  justify-content: space-between;
  cursor: move;
  font-size: 14px;
  user-select: none;

  .expand {
    .expand-icon {
      cursor: pointer;
    }
  }

  .table-cell {
    text-align: center;
    padding: 10px;
    box-sizing: border-box;
    flex-shrink: 0;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;

    .btn-container {
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
    }
  }

  &.noMove {
    cursor: default;
  }
}

.table-expand_container {
  background-color: #ffffff;
  padding: 15px 15px 15px 50px;
  border-bottom: 1px solid #e4e7ed;
}

.table-row-mouse-enter {
  background: #f0f2f5;
}

.empty {
  text-align: center;
  line-height: 50px;
  color: #909399;
  border: 1px solid #e4e7ed;
  border-top: none;
  font-size: 14px;
}

.switch {
  position: relative;

  .cover {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    cursor: pointer;
  }
}
:deep(.el-cascader) {
  .el-input .el-input__suffix-inner .el-icon {
    &::before {
      display: none;
    }
  }
}
</style>
